<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\api\model\v1;
use think\Model;
use think\facade\Db;

class User extends Model{
    //新增编辑
	static function edit($lang,$id,$data){
		if($id > 0){//编辑
			$user = User::find($id);
			$user->where('id',$id)->save($data);
			//更新auth_group_access表...
		}else{//新增
			//会员注册默认会员组
			$authGroupWhere[] = ['lang','=',$lang]; $authGroupWhere[] = ['is_admin','=',0];
		    $authGroupRs = Db::name('auth_group')->where($authGroupWhere)->order('sequence desc')->find();
		    //执行操作
			$user = new User;
			$user->save($data);
		    //添加auth_group_access表
			Db::name('auth_group_access')->insert(['group_id'=>$authGroupRs['id'],'uid'=>$user->id]);
		}
		return $user->id;
	}

    /*判断是否持久登录
    * $lang 语言模块
    */
    static function checkLong($lang){
        $userRs = self::checkRemember();
        if($userRs !== false){
            //写入session
            session('userid',$userRs['id']);
        }else{
            return false;
        }
    }

    //验证用户是否勾选“保存一月”
    static function checkRemember(){
        $arr = array(); $thistime = time(); $identifier = ''; $token = '';
        if(cookie('?bmkj_auth')){
            list($identifier,$token) = explode(':',cookie('bmkj_auth'));
        }
        if(!ctype_alnum($identifier) or !ctype_alnum($token)){
            return false;
        }
        $userWhere[] = ['identifier','=',$identifier]; $userWhere[] = ['token','=',$token];
        $userRs = Db::name('user')->where($userWhere)->find();
        if(!empty($userRs)){
            if($thistime < $userRs['timeout']){
                return $userRs;
            }
        }
        return false;
    }

	/**获取用户信息
    * @userid 用户ID
    **/
    static function getUser($userid){
        if(!session('?userid')) return null;
        $rs = Db::view('user','*')
            ->view('auth_group_access','uid','auth_group_access.uid=user.id')
            ->view('auth_group',['id'=>'g_id','parentid'=>'g_parentid','upgrade'=>'g_upgrade','discount'=>'g_discount','current_price'=>'g_current_price','title'=>'g_title','signid'=>'g_signid','is_distributor','level_1','level_2','level_3'],'auth_group.id=auth_group_access.group_id')
            ->where('user.id',$userid)
            ->find();
        return $rs;
    }

    /*信息（down）表的折扣
    * callback返回类型：num返回折扣值（详情页用），str返回状态（判断是否可直接下载用can_down方法）
    * discount 为信息（down）表的user_discount字段值
    * groupid 为session('groupid')的值
    */
    static function down_discount($callback = 'str',$discount = 1,$groupid = ''){
        $final_discount = 1;
        $userDiscountArr = explode('@', $discount);
        foreach ($userDiscountArr as $i => $discountArr) {
            $valArr = explode(':', $discountArr);
            if($valArr[0] == $groupid){
                if($callback == 'str'){//判断是否可直接下载，can_down方法用
                    if($valArr[1] <= 0){
                        return 'yes';
                        break;
                    }
                }
                $final_discount = $valArr[1]/100;
            }
        }
        return $final_discount;
    }

    /*会员组（auth_group）表的折扣
    * group_discount 为session('group_discount')的值
    * tabledir 模型表
    */
    static function group_discount($group_discount,$tabledir = 'down'){
        $final_discount = 1;
        $group_discount_arr = explode('@', $group_discount);
        foreach ($group_discount_arr as $j => $table_discount) {
            $table_discount_arr = explode(':', $table_discount);
            
            // 转为小写字母
            $general = new \common\General();
            $tabledir = $general->capital_to_underline($tabledir);

            //如：down == down
            if($table_discount_arr[0] == $tabledir){
                $final_discount = $table_discount_arr[1]/100;
                break;
            }
        }
        return $final_discount;
    }

    /**
     * 会员列表
     * userid 会员ID
     * listNum 每页显示数量
     * notGroupid 排除的会员组ID
     * notid 排除的会员ID
     * field 会员字段
     * order 排序
     * signid 状态值
     * keyword 关键词
    */
    static function index($userid = '', $listNum = 12, $notGroupid = '', $notid = '', $field = 'id,username,nickname,company,mobile,email,telephone,wechat,qq,avatar', $order = 'user.lastlogin desc', $signid = 1,$keyword = ''){
        $where = array(); $pageParam = array('keyword'=>$keyword);
        if(!empty($signid)){
            $where[] = ['user.signid','=',$signid];
            $pageParam += array('signid'=>$signid);
        }
        // 我推荐的会员
        if(!empty($userid)){
            $where[] = ['user.parentid','=',$userid];
            $pageParam += array('parentid'=>$userid);
        }
        if(!empty($notid)){
            $where[] = ["user.id",'not in',$notid];
            $pageParam += array('notid'=>$notid);
        }
        if(!empty($notGroupid)){
            $where[] = ["auth_group.id",'not in',$notGroupid];
            $pageParam += array('not_groupid'=>$notGroupid);
        }
        
        $rs = Db::view('user',$field)->view('auth_group_access','uid','auth_group_access.uid=user.id')
            ->view('auth_group','is_admin,title','auth_group.id=auth_group_access.group_id')->where($where)
            ->where("user.mobile|user.email|user.username|user.nickname|user.company|user.telephone|user.wechat|user.qq",'like',"%$keyword%");
        // 随机排序
        if($order == 'rand'){
            $rs = $rs->orderRand();
        }else{
            $rs = $rs->order($order);
        }
        $rs = $rs->paginate([
            'list_rows'=> $listNum,
            'query'=> $pageParam,
        ]);
            
        return $rs;
    }
}